import axios, { type AxiosRequestConfig } from 'axios';
import type { RequestOptions, ResponseData } from '../types';
import config from '@/utils/request/config';
import { useUserStore } from '@/stores';

const { token } = useUserStore();

const axiosAdapter = async <T>(url: string, options: RequestOptions): Promise<ResponseData<T>> => {
  const axiosConfig: AxiosRequestConfig = {
    url,
    method: options.method || 'GET',
    headers: {
      ...config.DEFAULT_HEADERS,
      ...(token ? { 'X-XSRF-TOKEN': token } : {}),
      ...options.headers,
    },
    params: options.params,
    data: options.data,
    timeout: options.timeout || config.TIMEOUT,
    withCredentials: true,
    signal: options.signal,
  };

  try {
    const response = await axios(axiosConfig);
    return {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers as Record<string, string>,
      data: response.data as T,
    };
  } catch (error) {
    if (axios.isCancel(error)) {
      throw new Error('Request cancelled');
    }

    if (axios.isAxiosError(error) && error.response) {
      throw new Error(`HTTP error! status: ${error.response.status}`);
    }

    throw error;
  }
};

export default axiosAdapter;
